import axios from 'axios'
import Element from 'element-ui'
import router from './router'
import store from './store'

//
axios.defaults.baseURL = 'http://localhost:8234'

//拦截
axios.interceptors.request.use(config => {
    //console.log(config)
    let token = localStorage.getItem('token');
    if(token) {
        config.headers['Authorization'] = token
    }
    return config;
});

axios.interceptors.response.use(response => {
    let res = response.data;

    if(200 == res.code) {
        return response;
    }

    Element.Message.error(res.msg, {duration: 2*1000});
    return Promise.reject(res.msg);
  },
  err => {
    //console.log('err', err.response)
    if(err.response.data && 200 != err.response.data.code) {
        let msg = err.response.data.msg || err.response.data.message
        Element.Message.error(msg, {duration: 2*1000});
    }
    if(401 == err.response.status) {
        store.commit('removeTokenUserInfo')
        router.push('/login')
    } else if(500 == err.response.status) {
        //Element.Message.error(err.response.data.message, {duration: 1000});
        //store.commit('removeTokenUserInfo')
    }
    return Promise.reject(err);
  }
);

